package com.g.ocache.impl.index;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import com.g.ocache.enums.SortingOrder;
import com.g.ocache.index.Leaf;
import com.g.ocache.index.Node;


/**
 * 
 * @author zhangyf
 * @param <K>
 * @param <V>
 */
public class BasicLeaf<K, V> extends AbstractNode<K, V> implements Leaf<K, V> {
	//
	private final TreeSet<K> keys;
	
	/**
	 * 
	 */
	public BasicLeaf(Object id, Node<K, V> parent) {
		this(id, parent, null);
	}
	
	public BasicLeaf(Object id, Node<K, V> parent, Comparator<K> comparator) {
		//
		super(id, parent);
		
		//
		if(comparator == null) {
			this.keys = new TreeSet<K>();
		} else {
			this.keys = new TreeSet<K>(comparator);
		}
	}
	
	/**
	 * 
	 */
	public int getKeyCount() {
		return keys.size();
	}
	
	public boolean addKey(K key) {
		return keys.add(key);
	}

	public boolean removeKey(K key) {
		//
		boolean r = keys.remove(key);
		
		//
		if(getKeyCount() == 0) {
			getParent().removeChild(getId());
		}
		return r;
	}
	
	public List<K> getKeys() {
		return new LinkedList<K>(keys);
	}
	
	public List<K> getKeys(SortingOrder order) {
		//
		List<K> r = null;
		switch (order) {
		case asc:
			r = new LinkedList<K>(keys);
			break;
		case desc:
			r = reverse(keys);
			break;
		}
		return r;
	}

	/**
	 * 
	 */
	public void clear() {
		throw new UnsupportedOperationException();
	}
	
	public void removeChild(Object id) {
		throw new UnsupportedOperationException();
	}

	public void addChild(Object id, Node<K, V> child) {
		throw new UnsupportedOperationException();
	}
	
	public Node<K, V> getChild(Object id) {
		return null;
	}
	
	public List<Node<K, V>> getChildren() {
		return new ArrayList<Node<K, V>>(0);
	}
	
	public List<Node<K, V>> getChildren(Object from, boolean isFromInclusive, Object to, boolean isToInclusive, SortingOrder order) {
		return new ArrayList<Node<K, V>>(0);
	}
	
	/**
	 * 
	 */
	private LinkedList<K> reverse(SortedSet<K> set) {
		LinkedList<K> r = new LinkedList<K>();
		for(K key : set) {
			r.addFirst(key);
		}
		return r;
	}
}
